package com.factory.rest.controller;

import com.alibaba.fastjson.JSONObject;
import com.factory.common.bean.User;
import com.factory.common.bean.UserWx;
import com.factory.common.constant.ResultCode;
import com.factory.common.pojo.Result;
import com.factory.common.utils.HttpUtil;
import com.factory.common.utils.StringUtil;
import com.factory.rest.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 微信以及微信小程序的相关的接口
 *
 * @author JW
 * @version 1.0
 * @date 2020/11/24 16:00
 */
@RestController
@Slf4j
@RequestMapping("/rest/wx")
public class WxController {

    @Value("${jiexun.wxapp.appId}")
    private String appId ;

    @Value("${jiexun.wxapp.secret}")
    private String secret;

    @Autowired
    private UserService userService;

    /**
     * 小程序绑定
     *
     * @param param {<br>
     * code:"小程序授权code",<br>
     * <br>}
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody JSONObject param, HttpServletRequest request) {
        log.info("程序进入 微信小程序绑定方法,本次请求参数为:{}", param);

        String code = param.getString("code");

        if (StringUtil.isEmpty(code)) {
            return Result.fail("请求参数code错误");
        }

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        url = url.replace("APPID", appId)
                .replace("SECRET", secret)
                .replace("JSCODE", code);

        JSONObject json = HttpUtil.get2(url);
        log.debug("本次请求的url,{}", url);

        if (null == json) {
            return Result.fail("调用微信接口信息获取数据为空!");
        }
        log.debug("利用CODE换取openId结果:{}", json.toJSONString());

        if (json.containsKey("errcode") || (!json.containsKey("openid") && !json.containsKey("unionid"))) {
            return Result.fail("获取登录信息失败，请重新操作!");
        }

        log.info("本次获取到的授权信息为:{}", json);

        User user = userService.queryByOpenId(json.getString("openid"));
        if(null == user){
            return Result.fail(json.getString("openid"), ResultCode.NotBind.message,ResultCode.NotBind.code);
        }

        JSONObject jsonObject = userService.setSession(user);
        jsonObject.put("openid",json.getString("openid"));

        return Result.success(jsonObject);
    }

    /**
     * 小程序绑定
     *
     * @param param {<br>
     * code:"小程序授权code",<br>
     * mobile:"手机号码",verifyCode:"验证码", LoginUser:"微信信息", username:"登录名"
     * <br>}
     * @param request
     * @return
     */
    @RequestMapping("/binding")
    public Result binding(@RequestBody JSONObject param, HttpServletRequest request) {
        log.info("程序进入 微信小程序绑定方法,本次请求参数为:{}", param);

        String openid = param.getString("openid");
        if (StringUtil.isEmpty(openid)) {
            return Result.fail("请求参数openId错误");
        }else if(StringUtil.isEmpty(param.getString("username"))){
            return Result.fail("请求参数username错误");
        }else if(StringUtil.isEmpty(param.getString("password"))){
            return Result.fail("请求参数password错误");
        }

        Result result = userService.login(param.getString("username"), param.getString("password"));
        if(!result.isStatus()){
            return result;
        }

        if(null != userService.queryByOpenId(openid)){
            return Result.fail("您已绑定账号无需重复绑定!");
        }

        JSONObject data = (JSONObject) result.getData();

        User user = (User) data.get("user");

        UserWx userWx = new UserWx();
        userWx.setId(StringUtil.getUUID());
        userWx.setOpenId(openid);
        userWx.setUserId(user.getId());
        userWx.setAvatarurl(param.getString("avatarurl"));
        userWx.setNickname(param.getString("nickname"));
        userWx.setGender(param.getInteger("gender"));
        userWx.setCountry(param.getString("country"));
        userWx.setProvince(param.getString("province"));
        userWx.setCity(param.getString("city"));
        userWx.setStatus(1);
        userWx.setCreateDate(new Date());
        userService.insertWx(userWx);

        return Result.success(data,"绑定成功!");
    }
}
